#!/usr/bin/python
from derbyos import DerbyXML
from derbyos import Stopwatch
from derbyos import NSOde
from derbyos import BoutStates
import wx
import wxDerbyOS
from wxDerbyOS import UpdateOnMainThread, Stopwatcher, UpdateLabelOnMainThread, TeamRoster
import logging


class NSOdeScorekeeper(wx.Frame):
    def __init__(self, nsode):
        self.nsode = nsode
        super(NSOdeScorekeeper, self).__init__(None, title="Scorekeeper",
                                               size=(600, -1))
        self.listbox = wx.ListBox(self, -1, pos=(10, 55), size=(400 - 20, 200))

        def UpdateJams(obj, attr, value):
            self.updateJams()

        self.nsode.boutState.addObserver(UpdateOnMainThread(self, UpdateJams), "boutState")
        self.Bind(wx.EVT_LISTBOX, self.OnSelectJam, self.listbox)

        self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer3 = wx.BoxSizer(wx.HORIZONTAL)

        self.leadButton = wx.Button(self, -1, "Lead")
        self.Bind(wx.EVT_BUTTON, self.OnLead, self.leadButton)
        self.lostButton = wx.Button(self, -1, "Lost")
        self.Bind(wx.EVT_BUTTON, self.OnLost, self.lostButton)
        self.callButton = wx.Button(self, -1, "Call")
        self.Bind(wx.EVT_BUTTON, self.OnCall, self.callButton)
        self.newJamButton = wx.Button(self, -1, "New Jam")
        self.Bind(wx.EVT_BUTTON, self.OnNewJam, self.newJamButton)
        self.sizer2.Add(self.leadButton, 1, wx.EXPAND)
        self.sizer2.Add(self.lostButton, 1, wx.EXPAND)
        self.sizer2.Add(self.callButton, 1, wx.EXPAND)
        self.sizer2.Add(self.newJamButton, 1, wx.EXPAND)

        for i in range(0, 7):
            button = wx.Button(self, -1, str(i))
            self.Bind(wx.EVT_BUTTON, self.OnScore, button)
            self.sizer3.Add(button, 1, wx.EXPAND)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.listbox, 0, wx.EXPAND)
        self.sizer.Add(self.sizer2, 1, wx.EXPAND)
        self.sizer.Add(self.sizer3, 2, wx.EXPAND)

        self.roster = TeamRoster(self.nsode, self)

        def UpdateJamSkater(obj, attr, value):
            jam, sp = self.SelectedJam()
            if value is not None:
                self.nsode.Lineup(str(self.roster.team.id), str(value.id), "jammer", jam=str(jam.jamNumber),
                                  period=str(jam.EnclosingPeriod().periodNumber))
                self.updateJams()

        self.roster.addObserver(UpdateOnMainThread(self, UpdateJamSkater), 'currentSkater')
        self.baseSizer = wx.FlexGridSizer(wx.HORIZONTAL, 2, 1)
        self.baseSizer.Add(self.roster.sizer, 0, wx.EXPAND)
        self.baseSizer.Add(self.sizer, 1, wx.EXPAND)

        #Layout sizers
        self.SetSizer(self.baseSizer)
        self.SetAutoLayout(1)
        self.baseSizer.Fit(self)

        self.listIndex = []

    def OnSelectJam(self, event):
        jam, sp = self.SelectedJam()
        #print "Changing current skater to", jam.skater
        self.roster.currentSkater = jam.skater

    def OnScore(self, event):
        jam, sp = self.SelectedJam()
        if jam:
            score = event.EventObject.LabelText
            #print "Sending score",score,"for team", self.roster.team, "in jam", jam
            self.nsode.ScorePass(self.roster.team.id, score, jam=jam.jamNumber,
                                 period=jam.EnclosingPeriod().periodNumber)
        self.updateJams()

    def OnLead(self, event):
        pass

    def OnLost(self, event):
        pass

    def OnCall(self, event):
        pass

    def OnNewJam(self, event):
        pass

    def SelectedJam(self):
        if self.listbox.Selection == -1:
            return None, False
        return self.listIndex[self.listbox.Selection]


    def FormatJam(self, jam, starPass=False):
        retval = ""
        if starPass:
            retval = "SP"
        else:
            retval = str(jam['number'])
        retval += "\t"
        jammer = None
        lineup = jam.lineupForTeam(self.roster.team)
        #print "lineup for",self.roster.team.id,lineup
        if starPass:
            jammer = lineup['pivot']
        else:
            jammer = lineup['jammer']
        if jammer:
            retval = retval + jammer['number']
        else:
            retval += "???"

        events = jam.eventsForTeam(self.roster.team)
        scores = []
        noPass = True
        inj = False
        lead = False
        call = False
        lost = False
        inj = False
        for event in events:
            #print "event",event.tostring()
            if event.elementName == "injury":
                inj = True
            if event.skater == jammer or event.skater is None:
                if event.elementName == "pass":
                    scores.append(str(event['points']))
                    noPass = False
                elif event.elementName == "lead":
                    lead = True
                elif event.elementName == "lost-lead":
                    lost = True
                elif event.elementName == "penalty" and lead:
                    lost = True  # just in case
                elif event.elementName == "star-pass" and lead:
                    lost = True
                elif event.elementName == "call":
                    call = True
        if len(scores) == 0:
            noPass = True
            scores.append("-")
        if lost:
            retval += "-"
        else:
            retval += "."
        if lead:
            retval += "L"
        else:
            retval += "."
        if call:
            retval += "C"
        else:
            retval += "."
        if inj:
            retval += "I"
        else:
            retval += "."
        if noPass:
            retval += "N"
        else:
            retval += "."
        retval += "\t"
        retval += "\t".join(scores)
        return retval

    def updateJams(self):
        self.listbox.Clear()
        self.listIndex = []
        period = self.nsode.boutState.currentPeriod
        curjam = self.nsode.boutState.currentJam
        if period:
            for jam in period.jams():
                print "Adding jam", jam
                self.listIndex.append((jam, False))
                self.listbox.Append(self.FormatJam(jam))

#                if jam == curjam:
#                    self.listbox.Select(len(self.listIndex)-1)


if __name__ == '__main__':
    import derbyos.Defaults

    optionsParser = derbyos.Defaults.TeamOptionsParser()
    wxDerbyOS.testWX("Score Keeper", NSOdeScorekeeper, optionsParser=optionsParser)
